<?php
/**
 * SKU价格走向
 *
 * PHP Version 5
 *
 * @package    Ecga
 * @subpackage Models
 * @author     Farmer.Li <lixu_01@126.com>
 * @copyright  2010 Xingchangxinda Inc.
 * @version    SVN:$Id$
 */
namespace Project\Apps\Ecga\Models\Table;

use Project\Apps\Ecga\Library\Visitor;
use \Framework\System\Helper\HttpRequest;
use \Project\Apps\Ecga\Library\FusionCharts\MSLine;
/**
 * SKU价格走向
 *
 * @package   Ecga
 * @author    Farmer.Li <lixu_01@126.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: v0.1
 */
class SkuAnalyse extends EcgaTable
{
    /**
     * 表名称
     */
    public $name = 'SKU价格走向';
    
    public $desc = '查看指定SKU的所有渠道价格走向。';
    
    public $defaultSort = '';
    
    /**
     * 所有项目
     */
    protected $projects = array();
    /**
     * 当前查看的项目
     */
    protected $project = array();
    /**
     * 站点列表
     */
    protected $sites = array();
    
    /**
     * 构造
     *
     * @return void
     */
    public function __construct()
    {
        $this->projects = $this->getProjects();
        $this->sites = $this->getSites();
        parent::__construct();
    }
    
    /**
     * 设置数据表头
     *
     * @return void
     */
    protected function setHeaderGroups()
    {
        $request = HttpRequest::getInstance();
        $this->projectId = $pid = $request->get('projectId', 'int');
        $this->sku = $request->get('sku', 'string');
        $sku = model('Skus')->getBySKU($this->sku);
        $date = $request->get('date', 'string');
        $currentBatch = $request->get('batch', 'int');

        if (empty($this->sku) || empty($pid) || empty($currentBatch)) {
            return;
        }

        $batchConfig = model('Projects')->get($pid)->batchConfig;
        $batch = explode(',', $batchConfig);
        $this->headerGroups = array(
            '' => array(
                'sites' => array(
                    'name' => '销售渠道',
                    'lock' => 'true'
                )
            )
        );

        $this->batchHeadGroup = $this->_genBatchHeadGroup(
            $batch, 
            $date, 
            $currentBatch, 
            30
        );

        foreach ($this->batchHeadGroup as $value) {
            $key = $value['date'] . '-' . $value['batch'];
            $dateTitle = date('y-m-d', strtotime($value['date']));
            $data = array(
                'name' => $dateTitle . ' ' . $value['batch'] . ':00',
                'class' => 'floatRight'
            );
            $headerKey = $this->sku . '(' . $sku->title . ') 前30个采集批次';
            $this->headerGroups[$headerKey][$key] = $data;
        }
    }

    /**
     * 返回指定次数批次
     * 
     * @param array  $batch        项目批次数组
     * @param string $date         当前选择日期
     * @param int    $currentBatch 当前选择批次
     * @param int    $times        生成前批次数量
     * 
     * @return array
     */
    private function _genBatchHeadGroup($batch, $date, $currentBatch, $times)
    {
        $countBatch = count($batch) - 1;
        $current = array_search($currentBatch, $batch);
        $endBatch = end($batch);
        $return = array();
        for ($i = 0; $i < $times; $i++) { 
            if ($current == -1) {
                $current = $countBatch;
            }
            if ($batch[$current] == $endBatch && $i != 0) {
                $dateInt = strtotime('-1 days', strtotime($date));
                $date = date('Y-m-d', $dateInt);
            }
            $return[] = array(
                'date' => $date,
                'batch' => $batch[$current]
            );

            $current --;
        }
        return $return;
    }
    
    /**
     * 初始化筛选器
     *
     * @return void
     */
    protected function initFilters()
    {
        $request = HttpRequest::getInstance();

        $pid = $request->get('projectId', 'int');

        if (1 == count($this->projects)) {
            foreach ($this->projects as $value) {
                    $batch = $value['id'];
            }
            $pid = $batch;
        }
        
        if (!empty($pid)) {
            $batchConfig = model('Projects')->get($pid)->batchConfig;
            $tmpBatch = explode(',', $batchConfig);
            $currentBatch = array_combine($tmpBatch, $tmpBatch);
        } else {
            $currentBatch = array();
        }

        $this->filters = Filter::createFromMultiArray(
            array(
                'projectId' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => 0,
                    'bind' => $this->arrayToOptions($this->projects, 'id', 'projectName'),
                    'caption' => '项目',
                    'name' => 'projectId'
                ),
                'date' => array(
                    'type' => Filter::FILTER_TYPE_DATE,
                    'default' => date('Y-m-d'),
                    'caption' => '日期',
                    'validator' => new DateTimeValidator
                ),
                'batch' => array(
                    'type' => Filter::FILTER_TYPE_SELECT,
                    'default' => '',
                    'caption' => '批次',
                    'bind' => $currentBatch,
                    'name' => 'batch'
                ),
                'sku' => array(
                    'name' => 'sku',
                    'type' => Filter::FILTER_TYPE_TEXT,
                    'caption' => '要查看的P/N',
                    'readOnly' => false
                ),
                'site' => array(
                    'name' => 'site',
                    'type' => Filter::FILTER_TYPE_TEXT,
                    'caption' => '查看指定渠道,多个渠道使用" "(空格)分隔',
                    'size' => 60,
                    'readOnly' => false
                ),
            )
        );
    }
    
    /**
     * 填充数据
     *
     * @return void
     */
    protected function fillData()
    {
        $request = HttpRequest::getInstance();
        $getSite = str_replace('　', ' ', $request->get('site', 'string'));
        $getSite = trim($getSite);
        $siteArray = explode(' ', $getSite);
        if (empty($this->batchHeadGroup)) {
            return;
        }
        $siteArray = array_filter($siteArray);
        foreach ($this->sites as $site) {
            if (count($siteArray) != 0 && !in_array($site['cname'], $siteArray)) {
                continue;
            }
            if (!isset($this->rows[$site['id']])) {
                $this->rows[$site['id']] = $this->createDataRow();
            }
            $this->rows[$site['id']]['sites'] = $site['cname'];        
            
            foreach ($this->batchHeadGroup as $value) {
                $key = $value['date'] . '-' . $value['batch'];

                $this->rows[$site['id']][$key] = model('SkuPriceLogs')->getBySku(
                    $this->sku,
                    $this->projectId,
                    $value['date'],
                    $value['batch'],
                    $site['id']
                );
            }
        }
    }
    
    /**
     * 生成图表可用数据
     *
     * @return void
     */
    protected function createChartData()
    {
        if (!$this->rows) {
            return;
        }
        $skuAnalyData = $this->rows;

        // 根据sku获得产品名称
        $product = model('skus')->getBySKU($this->sku);
        $mop = !empty($product->mop) ? $product->mop : $product->srp * parent::SRP_MOP; 
        foreach ($this->batchHeadGroup as $values) {
            $showPrice = $values['date'] .'-'. $values['batch'];
            $showTime = $values['date'] .' '. $values['batch'].':00';
            foreach ($skuAnalyData as $value) {
                $priceAsMop[$value['sites']][$showTime] = floatval($value[$showPrice]);
                $priceAsMop['LINE'][] = array(
                    '1' => 'SRP标线:'.$product->srp,
                    '2' => 'MOP标线:'.$mop,
                    '3' => 'DSP标线:'.$product->dsp
                );
                $toASMop = new MSLine($title = 'SKU价格走向图');
                $toASMop->setData($priceAsMop);
                $this->chartData['MSLine']['toASMop'] = array(
                    'name' => $title,
                    'xml' => $toASMop->put()
                ); 
            }
        }
    }
}